﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.DataModel;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.UserControl;
using System.Text;

namespace Giaiphongmatbang
{
    public partial class ListVillages : System.Web.UI.Page
    {
        QLGPMBEntities db = new QLGPMBEntities();
        VillagesRepostory objXa = new VillagesRepostory();
        private bool IsPageRefresh = false;
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            ucPaging1.PageChange += new ucPaging.PagingHandler(BinDataVillage);
            ucPaging2.PageChange += new ucPaging.PagingHandler(BindDataProject);
            ucPaging3.PageChange += new ucPaging.PagingHandler(BindDataHouseHold);
            if (!IsPostBack)
            {
                ucPaging1.CurrentPage = 1;
                ucPaging1.PageSize = 50;
                ucPaging1.PageDisplay = 5;
                ucPaging2.CurrentPage = 1;
                ucPaging2.PageSize = 50;
                ucPaging2.PageDisplay = 5;
                ucPaging3.CurrentPage = 1;
                ucPaging3.PageSize = 50;
                ucPaging3.PageDisplay = 5;
                BinDataVillage();
                BindddlParent();
                txtVillageName.Text = string.Empty;
            }

            if (Page.IsPostBack)
            {
                if ((string)ViewState["postid"] != (string)Session["postid"].ToString() && ViewState["postid"] != null && Session["postid"] != null)
                    IsPageRefresh = true;
            }
            Session["postid"] = System.Guid.NewGuid().ToString();
            ViewState["postid"] = Session["postid"];
        }
        public void BinDataVillage()
        {
            int totalRow = 0;
            grvVillage.DataSource = new VillagesRepostory().GetAll(ucPaging1.PageSize, ucPaging1.CurrentPage, ref totalRow);
            ucPaging1.TotalRecord = totalRow;
            ucPaging1.Visible = (ucPaging1.TotalPage > 1);
            grvVillage.DataBind();
        }

        int proid
        {
            set { ViewState["proid"] = value; }
            get { return (int)ViewState["proid"]; }
        }

        protected void lbtVillage_Click(object sender, EventArgs e)
        {
            pnl1.Visible = false;
            pnl2.Visible = true;
            LinkButton lbt = (LinkButton)sender;
            villageID = int.Parse(lbt.CommandArgument);
            Village currentVillage = new VillagesRepostory().GetByID(villageID);
            BindDataProject();
            BindDataHouseHold();
            ltrVillageName.Text = " " + currentVillage.VillageName;
              
        }

        protected void lbtProject_Click(object sender, EventArgs e)
        {
            LinkButton lbt = (LinkButton)sender;
            int projectID = int.Parse(lbt.CommandArgument);
            proid = projectID;
            int totalRow = 0;
            grvHouseHold.DataSource = new VillagesRepostory().GetTotalHouseHold(villageID, projectID, ucPaging3.PageSize, ucPaging3.CurrentPage, ref totalRow);
            ucPaging3.TotalRecord = totalRow;
            ucPaging3.Visible = (ucPaging3.TotalPage > 1);
            grvHouseHold.DataBind();
        }

        int villageID
        {
            set { ViewState["villageID"] = value; }
            get { return (int)ViewState["villageID"]; }
        }
        protected void BindDataProject()
        {
            int totalRow = 0;
            grvProject.DataSource = new ProjectsRepository().GetProjectByVillageID(villageID, ucPaging2.PageSize, ucPaging2.CurrentPage, ref totalRow);
            ucPaging2.TotalRecord = totalRow;
            ucPaging2.Visible = (ucPaging2.TotalPage > 1);
            grvProject.DataBind();
            ltrTotalProjectInVillage.Text = " " + totalRow;
        }

        protected void BindDataHouseHold()
        {
            int totalRow = 0;
            grvHouseHold.DataSource = new VillagesRepostory().GetTotalHouseHold(villageID, ucPaging3.PageSize, ucPaging3.CurrentPage, ref totalRow);
            ucPaging3.TotalRecord = totalRow;
            ucPaging3.Visible = (ucPaging3.TotalPage > 1);
            grvHouseHold.DataBind();
        }

        protected void btnReturn2_Click(object sender, EventArgs e)
        {
            pnl1.Visible = true;
            pnl2.Visible = false;
        }

        public void BindddlParent()
        {
            ddlParent.DataSource = new DistrictsRepository().GetAll();
            ddlParent.DataTextField = "DistrictName";
            ddlParent.DataValueField = "DistrictID";
            ddlParent.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            hdfmodenew.Value = "True";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "showdialog();", true);            
        }

        protected void btnAddVillage_Click(object sender, EventArgs e)
        {
            if (!IsPageRefresh)
            {
                Boolean modenew = Boolean.Parse(hdfmodenew.Value);
                int idv = int.Parse(ddlParent.SelectedValue);
                if (txtVillageName.Text.Trim() == "")
                    return;
                if (modenew)
                {
                    District objdistrict = db.Districts.Where(d => d.DistrictID == idv).FirstOrDefault();
                    Village objvillag = new Village();
                    objvillag.VillageName = txtVillageName.Text.Trim();
                    objvillag.District = objdistrict;
                    objdistrict.Villages.Add(objvillag);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Thêm mới thành công')", true);
                }
                else
                {
                    Village objvillag = db.Villages.FirstOrDefault(p => p.VillageID == editvillage);
                    objvillag.VillageName = txtVillageName.Text.Trim();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Cập nhật thành công')", true);
                }
                db.SaveChanges();
            }
            BinDataVillage();
        }

        int editvillage
        {
            set { ViewState["editvillage"] = value; }
            get { return (int)ViewState["editvillage"]; }
        }
        protected void btnAll_Click(object sender, EventArgs e)
        {
            BindDataHouseHold();
        }

        protected void grvVillage_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string command = e.CommandName;
            if (command == "btnEdit")
            {
                int villageID = int.Parse(e.CommandArgument.ToString());
                Village objv = objXa.GetByID(villageID);
                hdfmodenew.Value = "False";
                editvillage = villageID;
                txtVillageName.Text = objv.VillageName;
                District d = objXa.GetDistrictBYVillage(villageID);
                ddlParent.SelectedValue = d.DistrictID.ToString();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "showdialog();", true);
                
            }
            else if(command=="btnDelete")
            {
                int villageID = int.Parse(e.CommandArgument.ToString());
                int total = 0;
                int a = 0, b = 0;
                Project objp = new ProjectsRepository().GetProjectByVillageID(villageID, a, b, ref total).FirstOrDefault();
                if (total > 0)
                {
                    string tb = "<script type='text/javascript'>alert('Không thể xóa xã đang có dự án');window.location='/ListVillages.aspx'</script>";
                    Response.Write(tb);
                }
                else
                {
                    if (objXa.GetByID(villageID) != null)
                    {
                        objXa.DeleteByID(villageID);
                        objXa.Save();
                    }
                    BinDataVillage();
                }
            }
            
        }

        protected void grvVillage_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (Session["User"] == null || !(new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.ManagerCategories)))
            {
                grvVillage.Columns[2].Visible=false;
                btnAdd.Visible = false;
            }
        }

    }
}